const http = require("axios");
const crypto = require("crypto"); // crypto 加密模块
const config = require("@conf/config");
const { decryptByAES, encryptSha1 } = require("@util/index");
const { saveUserInfo } = require("@controller/user");

function authorizeMiddleware(req, res, next) {
  return authMiddleware(req).then((result) => {
    res["auth_data"] = result;
    return next();
  });
}

function authMiddleware(req) {
  const { appid, secret } = config;
  const { code, encryptedData, iv } = req.body;
  if ([code, encryptedData, iv].some((_) => !_)) {
    return {
      result: -1,
      errMsg: "缺少参数字段",
    };
  }
  return fetchSessionKey(code, appid, secret)
    .then(({ session_key }) => {
      
      // 选择加密算法生产自己的登录标识
      const skey = encryptSha1(session_key);
      
      // 数据解密
      const decryptedData = decryptByAES(encryptedData, session_key, iv, appid);
      return saveUserInfo({
        userInfo: decryptedData,
        session_key,
        skey,
      });
    })
    .catch((err) => {
      return {
        result: -3,
        errMsg: JSON.stringify(err),
      };
    });
}

// 获取 session_key 和 openid
function fetchSessionKey(code, appid, secret) {
  return http({
    url: "https://api.weixin.qq.com/sns/jscode2session",
    method: "GET",
    params: {
      appid,
      secret,
      js_code: code,
      grant_type: "authorization_code",
    },
  }).then((res) => {
    const { openid, session_key, errmsg } = res.data || {};
    if (!openid || !session_key) {
      return {
        result: -2,
        errMsg: errmsg || "返回数据字段不完成",
      };
    } else {
      return res.data;
    }
  });
}

module.exports = authorizeMiddleware;
